package com.whli.jee.system.service.impl;

import com.whli.jee.common.exception.BusinessException;
import com.whli.jee.common.web.dao.IBaseDao;
import com.whli.jee.common.web.service.impl.BaseServiceImpl;
import com.whli.jee.system.dao.ISysRoleDao;
import com.whli.jee.system.dao.ISysUserRoleDao;
import com.whli.jee.system.entity.SysRole;
import com.whli.jee.system.service.ISysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Service("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole> implements ISysRoleService {

	@Autowired
	private ISysRoleDao sysRoleDao;
	@Autowired
	private ISysUserRoleDao sysUserRoleDao;

	@Override
	public IBaseDao<SysRole> getDao() {
		return sysRoleDao;
	}

	@Override
	public int delete(String id) {
		List<String> userIds = sysUserRoleDao.listUserByRole(id);
		if (!CollectionUtils.isEmpty(userIds)){
			throw new BusinessException("-1","该角色下有授权用户，不予删除");
		}

		return super.delete(id);
	}

	@Override
	public int deleteBatch(List<String> ids) {
		for (String id : ids){
			SysRole role = getByPK(id);
			List<String> userIds = sysUserRoleDao.listUserByRole(id);
			if (!CollectionUtils.isEmpty(userIds)){
				throw new BusinessException("-1","角色【"+role.getNo()+"】下有授权用户，不予删除");
			}
		}
		return super.deleteBatch(ids);
	}

	@Override
	public List<SysRole> listByUserId(String userId) {
		List<SysRole> roles = null;
		if(StringUtils.isNotBlank(userId)){
			roles = sysRoleDao.listByUserId(userId);
		}
		return roles;
	}

	@Override
	public SysRole validByNo(String no, String id) {
		return sysRoleDao.validByNo(no,id);
	}
}
